package com.zsl.controller.File;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet(name = "GetStaticFile", urlPatterns = "/staticFilepath/*")
public class GetStaticFile extends HttpServlet {
    private static final String JPG = "image/jpeg;";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取路径地址
        StringBuffer url = request.getRequestURL();
        //读取配置信息
        ResourceBundle resource = ResourceBundle.getBundle("webConfig");
        //获取设置的静态文件目录
        String staticFilepath_name = resource.getString("staticFilepath.name");
        //动态设置提取文件名正则表达式
        Pattern r = Pattern.compile(".*" + staticFilepath_name + "(.*)");
        Matcher m = r.matcher(url);
        if (!m.find()) {
            System.out.println("没有找到匹配");
            response.setStatus(500);
            return;
        }
        //组装文件路径
        String filepath = resource.getString("staticFilepath.root") + "\\" + m.group(1);
        filepath = filepath.replace("/", "\\");
        //查找文件是否存在
        File f = new File(filepath);
        if (!f.exists()) {
            response.setStatus(404);
        }
        //获取输入文件流
        FileInputStream inputStream = new FileInputStream(f);
        int size = inputStream.available();
        byte[] data = new byte[size];
        inputStream.read(data);
        inputStream.close();
        //TODO 判断文件类型
        //是一张图片
        if (filepath.toLowerCase().endsWith(".jpg")) {
            //设置返回的文件类型
            response.setContentType(JPG);
            ServletOutputStream out = response.getOutputStream();
            out.write(data);
        }
    }
}
